package com.jianye.recycdona.model.fragment.home;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.jianye.recycdona.R;
import com.jianye.recycdona.control.bean.addressJson;
import com.jianye.recycdona.control.http.ReserveHttp;
import com.jianye.recycdona.model.utils.CheckNetWork;
import com.jianye.recycdona.model.utils.GetJsonDataUtil;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class Add_addressInfoActivity extends AppCompatActivity {




    //city
    private List<addressJson> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    private static boolean isLoaded = false;

    EditText name,phone,detaile;
    TextView city;
    private SharedPreferences sp;


    //修改地址信息
    Intent intent;
    private int id;
    private String nameup,cityup,phoneup,detaiup,status;
    private TextView delete;
    private TextView updata;
    private TextView tobar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_add_address_info);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        ActionBar actionBar=getSupportActionBar();
        if (actionBar!=null){
            actionBar.hide();
        }

        initFindViewID();    //数据初始化

    }

    //数据初始化
    private void initFindViewID() {

        city =findViewById(R.id.edt_add_city);
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);//解析城市数据

        tobar=findViewById(R.id.address_tobartitle);
        name=findViewById(R.id.edt_add_username);
        phone=findViewById(R.id.edt_add_phone);
        detaile=findViewById(R.id.edt_add_detailed);
        delete=findViewById(R.id.address_delete);//删除/上一页
        updata=findViewById(R.id.sava_addressinfo);

        sp = getSharedPreferences("config", MODE_PRIVATE);//confi 文件名

        //*************************
        intent=getIntent();
        // 标识为当前为页面状态 修改，删除
        id=intent.getIntExtra("id",0);
        status=intent.getStringExtra("status");
        nameup=intent.getStringExtra("name");
        phoneup=intent.getStringExtra("phone");
        cityup=intent.getStringExtra("city");
        detaiup=intent.getStringExtra("detai");

        Log.d("upadtaaddress", "data------------>"+id+status+nameup+cityup+detaiup);

        if (status!=null){

            if (status.equals("updata")){
                tobar.setText("修改地址");
                name.setText(nameup);
                phone.setText(phoneup);
                city.setText(cityup);
                detaile.setText(detaiup);
                delete.setText("删除");
                updata.setText("修改");
            }
        }else {
            status="0";
        }

    }




    /**
     *返回上一页
     */

    public void addinfofinish(View view) {

        //删除
        if (delete.getText().toString().equals("删除")){

            AlertDialog.Builder builder = new AlertDialog.Builder(Add_addressInfoActivity.this);
            AlertDialog alert = builder.setIcon(R.drawable.img_default)
                    .setTitle("系统提示：")
                    .setMessage("确定删除?")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    })
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            ReserveHttp.getMyOkHttp().deleteAddress(id+"");

                            Toast.makeText(Add_addressInfoActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }).create();


            alert.show();





        }else {
            //返回上一页
            finish();
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS://解析完成
//                    Toast.makeText(Add_addressInfoActivity.this, "解析完成", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    Toast.makeText(Add_addressInfoActivity.this, "城市解析出错了", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    //Gson 解析
    public ArrayList<addressJson> parseData(String result) {
        ArrayList<addressJson> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                addressJson entity = gson.fromJson(data.optJSONObject(i).toString(), addressJson.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    //解析省份数据
    private void initJsonData() {
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<addressJson> jsonBean = parseData(JsonData);//用Gson 转成实体
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                cityList.add(cityName);//添加城市
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表
                city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);

            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }



    //城市选择事件监听
    public void city(View view) {
        InputMethodManager imm = (InputMethodManager) Add_addressInfoActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
        // 隐藏软键盘
        // 隐藏软键盘
        if (imm != null) {
            imm.hideSoftInputFromWindow(Add_addressInfoActivity.this.getWindow().getDecorView().getWindowToken(), 0);
        }


        if (isLoaded) {
            showPickerView();//显示城市dalog
        } else {
            Toast.makeText(Add_addressInfoActivity.this, "请稍等数据正在路上", Toast.LENGTH_SHORT).show();
        }
    }

    //显示
    private void showPickerView() {

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ?
                        options1Items.get(options1).getPickerViewText() : "";

                String opt2tx = options2Items.size() > 0
                        && options2Items.get(options1).size() > 0 ?
                        options2Items.get(options1).get(options2) : "";

                String opt3tx = options2Items.size() > 0
                        && options3Items.get(options1).size() > 0
                        && options3Items.get(options1).get(options2).size() > 0 ?
                        options3Items.get(options1).get(options2).get(options3) : "";

                String tx = opt1tx + opt2tx + opt3tx;
                city.setText(tx);
//                Toast.makeText(Add_addressInfoActivity.this, tx, Toast.LENGTH_SHORT).show();
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();

    }


    /**
     * 保存数据
     * @param view
     */
    public void sava_address_info(View view) {

        final String nameadd = name.getText().toString().trim();
        final String phoneadd = phone.getText().toString().trim();
        final String cityadd = city.getText().toString().trim();
        final String detaiadd = detaile.getText().toString().trim();
        if (TextUtils.isEmpty(nameadd)){
            Toast.makeText(this, "请输入收货人", Toast.LENGTH_SHORT).show();
        }else if (TextUtils.isEmpty(phoneadd)){
            Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
        }else if (!CheckNetWork.isValidPhoneNumber(phoneadd)){
            Toast.makeText(this, "请检查手机号格式", Toast.LENGTH_SHORT).show();
        }else if (cityadd.equals("省/市/区/县")){
            Toast.makeText(this, "请选择城市所在地", Toast.LENGTH_SHORT).show();
        }else if (TextUtils.isEmpty(detaiadd)){
            Toast.makeText(this, "请输入街道门牌信息", Toast.LENGTH_SHORT).show();
        }else{
            /***
             * 修改地址
             * 根据ID修改地址信息
             */
            //修改地址
            String up=updata.getText().toString();
            if (up.equals("修改")){
                //修改地址String id,String name,String phone,String city,String detai
                String nametx=name.getText().toString().trim();
                String phonetx=phone.getText().toString().trim();
                String citytx=city.getText().toString().trim();
                String detaitx=detaile.getText().toString().trim();

                try {
                    ReserveHttp.getMyOkHttp().putAddressinfo(id+"",nametx,phonetx,citytx,detaitx);

                } catch (ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }

                Log.e("data", "sava_address_info: "+id+nameup+phoneup+cityup+detaiup);
                Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
                finish();

            }else {

                //新增地址
                String paretId=sp.getString("id","");
                try {
                    int code=ReserveHttp.getMyOkHttp().postAddresss(paretId,nameadd,phoneadd,cityadd,detaiadd);
                    Log.e("codeAdd——Address",code+"");
                } catch (ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }


                Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
                finish();
                Log.e("addressinfo","---------------->"+nameadd+phoneadd+cityadd+detaiadd);

            }







        }


    }

    public void addressFinish(View view) {
        finish();
    }
}